﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MedicalSystem.SmartReport.Access;
using System.Configuration;
using System.Diagnostics;
using MedicalSystem.SamrtReport.Library;

namespace MedicalSystem.SamrtReport.Tools
{
    public partial class DataConnectionSettingFrm : Form
    {
        public DataConnectionSettingFrm()
        {
            InitializeComponent();
        }
        private string _connectionString = string.Empty;
        private string _providerName = string.Empty;
        private string _userId = string.Empty;
        private string _password = string.Empty;
        private string _serverIp = string.Empty;
        private string _connectionStringName = string.Empty;

        public string ConnectionStringName
        {
            get
            {
                return _connectionStringName;
            }
        }
        public string ConnectionString
        {
            get {return this._connectionString;}
            
        }
        public string ProviderName
        {
            get { return this._providerName; }

        }
        private void DataConnectionSettingFrm_Load(object sender, EventArgs e)
        {
            this.comboBox1.SelectedIndex = 0;
            this.textBox3.Focus();
            CustomFormHepler.ShowForm(this);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBox1.Text))
            {
               this.errorProvider1.SetError(comboBox1,"请选择数据源类型");
                return;
            }
            if (string.IsNullOrEmpty(textBox3.Text))
            {
                this.errorProvider1.SetError(textBox3, "请输入服务器名/IP");
                return;
            }

            if (string.IsNullOrEmpty(textBox1.Text))
            {
                this.errorProvider1.SetError(textBox1, "请输入用户名");
                return;
            }
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                this.errorProvider1.SetError(textBox2, "请输入密码");
                return;
            }

            _providerName = comboBox1.Text;
            _serverIp = textBox3.Text;
            _userId = textBox1.Text;
            _password = textBox2.Text;

            IDatabase database = DatabaseFactory.CreateDatabase(_serverIp, _userId, _password, _providerName);

            bool passed = database.ConnectionTest();

            if (!passed)
            {
                MessageBox.Show("数据库连接测试失败!", "提示框", MessageBoxButtons.OK, MessageBoxIcon.Error);
                comboBox2.Enabled = false;
                button2.Enabled = false;
            }
               
            else
            {
                MessageBox.Show("数据库连接成功!", "提示框", MessageBoxButtons.OK, MessageBoxIcon.Information);

                comboBox2.Enabled = _providerName != "System.Data.OracleClient";
                comboBox2.Items.Clear();
                if (_providerName == "System.Data.SqlClient")
                {
                    DataTable dt = database.GetDatabaseNames();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        comboBox2.Items.Add(dt.Rows[i][0].ToString());
                    }
                }
                else
                {
                    button2.Enabled = true;
                }

                

            }
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
           this.button2.Enabled = !string.IsNullOrEmpty(this.comboBox2.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.comboBox2.Text) && _providerName=="System.Data.SqlClient")
                return;

            if (string.IsNullOrEmpty(this.textBox4.Text) && this.checkBox1.Checked)
            {
                this.errorProvider1.SetError(this.textBox4, "请输入一个数据库的逻辑名称,建议使用产品的名称命名此数据库逻辑名");
                return;
            }
            if (_providerName == "System.Data.SqlClient")
            {
                _connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", _serverIp, this.comboBox2.Text, _userId, _password);
            }
            else
            {
               _connectionString = string.Format("Data Source={0};Persist Security Info=True;User ID={1};Password={2}", _serverIp,  _userId, _password);
            }
            if (this.checkBox1.Checked)
            {
               
                try
                {
                    Configuration exeConfig = ConfigurationManager.OpenExeConfiguration("SamrtReport.exe");
                    ConnectionStringSettings setting = new ConnectionStringSettings(this.textBox4.Text, _connectionString, _providerName);
                    exeConfig.ConnectionStrings.ConnectionStrings.Add(setting);

                    exeConfig.Save();
                    _connectionStringName = this.textBox4.Text;
                    ConfigurationManager.RefreshSection("connectionStrings");
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("保存数据库连接字符串{0}时发生错误:{1}", this.textBox4.Text, ex.Message), "Error");
                }
               

                Trace.WriteLine(string.Format("已保存数据库连接字符串{0}", this.textBox4.Text));
            }
            this.DialogResult = DialogResult.OK;

        }
    }
}
